package com.yxqz.filesystem.service;

import com.alibaba.fastjson.JSON;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.yxqz.filesystem.dao.FileSystemRepository;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @author 鱼香茄子
 * @data 2021/11/5
 */
@Service
public class FileSystemService {
    @Value("${yxqz.fastdfs.tracker_servers}")
    String tracker_servers;
    @Value("${yxqz.fastdfs.connect_timeout_in_seconds}")
    int connect_timeout_in_seconds;
    @Value("${yxqz.fastdfs.network_timeout_in_seconds}")
    int network_timeout_in_seconds;
    @Value("${yxqz.fastdfs.charset}")
    String charset;
    //    注入文件管理接口（Mongo）
    @Autowired
    FileSystemRepository fileSystemRepository;

    /**
     * 上传文件
     *
     * @param multipartFile
     * @param filetag
     * @param businesskey
     * @param metadata
     * @return
     */
    public UploadFileResult upload(MultipartFile multipartFile, String filetag, String businesskey, String metadata) {


        if (multipartFile == null) {
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_USERISNULL);
        }
//        将文件上传到fastDFs中，得到一个文件的id
        String fildid = fdfs_upload(multipartFile);
        if (StringUtils.isEmpty(fildid)) {
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }

        //        将文件id以及其他信息存储到mongo中
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileId(fildid);
        fileSystem.setFilePath(fildid);
        fileSystem.setFiletag(filetag);
        fileSystem.setBusinesskey(businesskey);
        fileSystem.setFileName(multipartFile.getOriginalFilename());
        fileSystem.setFileType(multipartFile.getContentType());
        if (StringUtils.isNotEmpty(metadata)) {
            try {
                Map map = JSON.parseObject(metadata, Map.class);
                fileSystem.setMetadata(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS, fileSystem);

    }


    /**
     * @param multipartFile 上传的文件
     * @return 文件的id
     */
    private String fdfs_upload(MultipartFile multipartFile) {
//        初始化fastDFS环境
        initfdfsConfig();
//        创建一个tracker客户端
        TrackerClient trackerClient = new TrackerClient();
        try {
            TrackerServer connection = trackerClient.getConnection();
//            得到storage服务
            StorageServer storeStorage = trackerClient.getStoreStorage(connection);
//            创建一个Storage客户端上传文件
            StorageClient1 storageClient1 = new StorageClient1(connection, storeStorage);
//            得到文件的字节
            byte[] bytes = multipartFile.getBytes();
//            获取文件（原始名称）
            String originalFilename = multipartFile.getOriginalFilename();
//            获取文件的扩展名
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            try {
                String fileID = storageClient1.upload_appender_file1(bytes, substring, null);
                return fileID;
            } catch (MyException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }


    /**
     * 初始化fastdfs环境
     */
    private void initfdfsConfig() {
//        初始化服务器tracker_servers 多个 tracker_servers 用英文逗号分隔
        try {
            ClientGlobal.initByTrackers(tracker_servers);
            ClientGlobal.setG_charset(charset);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FS_INITERROR);
        }
    }
}
